#!-*- coding:utf-8 -*-

import cgi
import traceback
import base64
import logging

import wsgiref.handlers
from google.appengine.api import urlfetch
from google.appengine.ext import db
import os, sys, re
import string
import datetime
from google.appengine.ext import webapp
from google.appengine.api import images
from google.appengine.api import users
from xml.dom import minidom

import constants


class Img3D(webapp.RequestHandler):

  def get(self):
    cmd = self.request.get("cmd")
    
    self.response.out.write('''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>3D Image Carousel</title>

<script type="text/javascript" src="/javascript/jquery/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="/javascript/jquery/Tween.js"></script>
<script type="text/javascript" src="/javascript/jquery/jquery.carousel3d.js"></script>
		
<style type="text/css" title="text/css">
		#buttonwrapper
		{
			width: 100px;
			height: 50px;
			position: relative;
		}
		
		#left
		{
			background: url(images/left.gif) bottom left no-repeat;
			width: 39px;
			height: 50px;
			float: left;
		}
		
		#right
		{
			background: url(images/right.gif) bottom left no-repeat;
			width: 39px;
			height: 50px;
			float: right;
		}

 		#holder_images { display: none; }
		#carousel img  { border: 2px solid #ddd;		}
		#carousel img.link:hover{ border: 4px solid #0e0893;	}
</style>

<script type="text/javascript">
jQuery(function($) {

// $("#carousel").html($("#holder_images").html()).carousel3d({ control: 'continuous', speed: 1, centerX: $('#carousel').offset().left + $('#carousel').width()/2 }); 

 $("#carousel").html($("#holder_images").html()).carousel3d({ control: 'buttons', centerX: $('#carousel').offset().left + $('#carousel').width()/2 }); 
 });
</script>

</head>
<body>3D TEST

	<div id="carousel"></div>	

    ''')

    if cmd == "test1":
      self.response.out.write('''
	<div id="holder_images">
<img class="link" title="to make an image a page link, add class 'link' and set the longdesc attr to a web address" src="images/jquery_plugins.png" alt="jquery_plugins" width="500" height="375" longdesc="http://jquery.com/" /> 
<img title="beach 1" src="/images/sinatra_beach_1.jpg" alt="beach_1" width="500" height="375" /> 
<img title="beach 2" src="/images/sinatra_beach_2.jpg" alt="beach_2" width="500" height="375" /> 
<img title="beach 3" src="/images/sinatra_beach_3.jpg" alt="beach_3" width="500" height="375" /> 
<img title="beach 4" src="/images/sinatra_beach_4.jpg" alt="beach_4" width="500" height="375" /> 
<img title="beach 5" src="/images/sinatra_beach_5.jpg" alt="beach_5" width="500" height="375" /> 
<img title="beach 6" src="/images/sinatra_beach_6.jpg" alt="beach_6" width="500" height="375" /> 
<img title="beach 7" src="/images/sinatra_beach_7.jpg" alt="beach_7" width="500" height="375" /> 
<img title="beach 8" src="/images/sinatra_beach_8.jpg" alt="beach_8" width="500" height="375" />
	</div>
    ''')

    if cmd == "test2":
      Title = u"ハリーポッター".encode("utf-8")
      url  = "http://webservices.amazon.co.jp/onca/xml?"
      url += "Service=AWSECommerceService&"
      url += "AWSAccessKeyId=" + constants.AWSAccessKeyId_KWIN786_PARAM + "&"
      url += "Operation=ItemSearch&"
      url += "SearchIndex=Books&"
      url += "Title=" + Title + "&"
      url += "Version=2008-04-07"

      result = urlfetch.Fetch(url)
      #self.response.out.write( result.content )

      dom = minidom.parseString(result.content)
      #r =dom.getElementsByTagName('Title')[0].firstChild.data
      #r =dom.getElementsByTagName('RequestId')[0].firstChild
      r =dom.getElementsByTagName('DetailPageURL')
      i = 0

      self.response.out.write( '''<div id="holder_images">
<img class="link" title="to make an image a page link, add class 'link' and set the longdesc attr to a web address" src="images/jquery_plugins.png" alt="jquery_plugins" width="500" height="375" longdesc="http://jquery.com/" />      
      ''')
      for rr in r:
        #print i,rr.firstChild.data.encode("utf8")
        i = i + 1
    
        url=dom.getElementsByTagName('DetailPageURL')[i-2].firstChild.data
        title=dom.getElementsByTagName('Title')[i-2].firstChild.data
        #self.response.out.write( title.encode("utf8") + "," + url.encode("utf8") )
        code = url.split("/")[5]
        code = str( code.split("%3F")[0] )
        content_url =  'http://images-jp.amazon.com/images/P/' + str(code) + ".09._SX300_.jpg" 
        #self.response.out.write('<br />content_url = ' + content_url + '<br />' )
        #self.response.out.write('<img src="' + content_url + '" />')

        dummy = url.split("/")
        l   = len(url)
        url = dummy[0] + "/" + dummy[1] + "/" + dummy[2] + "/" + dummy[4]
        dummy[5] = string.replace(dummy[5],'%26tag%3Dws','%26tag%3D' + constants.AMAZONTag_KWIN786_PARAM)
        url +=  "/" + dummy[5]


        self.response.out.write('''
        <img class="link" title="%s" src="%s" alt="%s" width="375" height="480" longdesc="%s" /> 
        ''' % (title,content_url, code,url ))

      self.response.out.write( '</div>' )	# holder_images 


      self.response.out.write('''
<a href="http://www.coswest.com/c/jquery/carousel3d/">http://www.coswest.com/c/jquery/carousel3d/</a>
</body>
</html>
    ''')

def main():
  application = webapp.WSGIApplication(
                                       [('/3DImage', Img3D),
					],
                                       debug=True)
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(application)
if __name__ == "__main__":
  main()
